package http

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"mall-portalv2/global"
	"mall-portalv2/internal/model"
	"mall-portalv2/internal/server/ctx"
	"mall-portalv2/library/common"
	"net/http"
	"time"
)

func OrderConfirmOrderHandlerFunc(c *gin.Context) {
	app := ctx.Gin{C: c}

	uidStr, isUid := c.Get("uid")
	if !isUid {
		global.Log.Error("uid不存在")
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, nil)
		return
	}
	UID := common.Str2Int64(fmt.Sprintf("%d", uidStr))

	type RequestBody struct {
		CrowdFundingId      int64 `json:"crowd_funding_id"`
		CrowdFundingThaliId int64 `json:"crowd_funding_thali_id"`
		ProductSkuId        int64 `json:"product_sku_id"`
		ProductId           int64 `json:"product_id"`
	}

	request := RequestBody{}
	if err := common.BindAndCheck(c, &request); err != nil {
		global.Log.Error("请求参数不正确", zap.Error(err))
		app.Response(http.StatusBadRequest, ctx.StatusBadRequest, err)
		return
	}

	global.Log.Info("映射完成", zap.Any("data", request))

	productAndCrowdFundingResult, err := svc.QueryProductAndCordFunding(c, request.CrowdFundingId, request.CrowdFundingThaliId, request.ProductSkuId, request.ProductId)
	if err != nil {
		global.Log.Error("mysql err", zap.Error(err))
		if err == gorm.ErrRecordNotFound {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, "找不到对应的商品记录")
			return
		} else {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
	}

	global.Log.Info("查询完毕", zap.Any("data", productAndCrowdFundingResult))

	// 添加到购物车

	resOrderConfirmResult := resOrderConfirm{}

	// TODO: 地址获取
	addressList, err := svc.QueryUmsMemberReceiveAddressAllWhereMemberID(context.Background(), UID)
	if err != nil {
		global.Log.Error("mysql err", zap.Error(err))
		if err == gorm.ErrRecordNotFound {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, "找不到对应的地址记录")
			return
		} else {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
	}

	resOrderConfirmResult.MemberReceiveAddressList = addressList

	// TODO: 优惠券的获取
	//couponDetailList, err := svc.QueryViewCouponDetail(context.Background(), UID, 1)
	//if err != nil {
	//	app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
	//	return
	//}

	//resOrderConfirmResult.MemberReceiveAddressList = couponDetailList

	//global.Log.Info("打印一下内容", zap.Any("couponDetailList", couponDetailList))

	// 获取用户积分

	userResult, err := svc.QueryUmsMemberWhereID(c, UID)
	if err != nil {
		global.Log.Error("mysql err", zap.Error(err))
		if err == gorm.ErrRecordNotFound {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, "找不到对应的用户的积分记录")
			return
		} else {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
	}

	resOrderConfirmResult.MemberIntegration = userResult.Integration

	// TODO: 获取积分使用条件
	userIntegrationSettingResult, err := svc.QueryUmsIntegrationConsumeSettingWhereID(c, 1)
	if err != nil {
		global.Log.Error("mysql err", zap.Error(err))
		if err == gorm.ErrRecordNotFound {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, "找不到对应的积分使用条件")
			return
		} else {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
	}
	resOrderConfirmResult.IntegrationConsumeSetting = userIntegrationSettingResult

	//	0 没有使用促销
	// 众筹商城
	//itemBt, _ := json.Marshal(productAndCrowdFundingResult)
	cartPromotionItemResult := cartPromotionItem{
		Id:           productAndCrowdFundingResult.ProductId,
		CreateDate:   productAndCrowdFundingResult.CfCreateTime,
		DeleteStatus: productAndCrowdFundingResult.DeleteStatus,
		Growth:       productAndCrowdFundingResult.GiftGrowth,
		Integration:  productAndCrowdFundingResult.GiftPoint,
		MemberId:     UID,
		//MemberNickname    : ,
		//ModifyDate        : productAndCrowdFundingResult.Modi,
		Price:             productAndCrowdFundingResult.OriginalPrice,
		ProductAttr:       productAndCrowdFundingResult.SkuSpData,
		ProductBrand:      productAndCrowdFundingResult.BrandName,
		ProductCategoryId: productAndCrowdFundingResult.ProductCategoryId,
		ProductId:         productAndCrowdFundingResult.ProductId,
		ProductName:       productAndCrowdFundingResult.Name,
		ProductPic:        productAndCrowdFundingResult.SkuPic,
		ProductSkuCode:    productAndCrowdFundingResult.SkuSkuCode,
		ProductSkuId:      productAndCrowdFundingResult.SkuID,
		ProductSn:         productAndCrowdFundingResult.ProductSn,
		ProductSubTitle:   productAndCrowdFundingResult.SubTitle,
		PromotionMessage:  "众筹活动",
		Quantity:          1,
		ServiceIds:        productAndCrowdFundingResult.ServiceIds,
		//RealStock:         productAndCrowdFundingResult.ProductId,
		//ReduceAmount:      productAndCrowdFundingResult.RecommandStatus,

		// sms_crowd_funding
		CfId:           productAndCrowdFundingResult.CfId,
		CfTitle:        productAndCrowdFundingResult.CfTitle,
		CfDeliveryDate: productAndCrowdFundingResult.CfDeliveryDate,

		// sms_crowd_funding_thali
		CftId:               productAndCrowdFundingResult.CftId,
		CftTitle:            productAndCrowdFundingResult.CftTitle,
		CftDescription:      productAndCrowdFundingResult.CftDescription,
		CftSort:             productAndCrowdFundingResult.CftSort,
		CftThaliPrice:       productAndCrowdFundingResult.CftThaliPrice,
		CftThaliDiscount:    productAndCrowdFundingResult.CftThaliDiscount,
		CftThaliCount:       productAndCrowdFundingResult.CftThaliCount,
		CftLockThaliCount:   productAndCrowdFundingResult.CftLockThaliCount,
		CftThaliLimitStatus: productAndCrowdFundingResult.CftThaliLimitStatus,
		CftThaliLimit:       productAndCrowdFundingResult.CftThaliLimit,
		CftStatus:           productAndCrowdFundingResult.CftStatus,
		CftCreateTime:       productAndCrowdFundingResult.CftCreateTime,
	}
	//json.Unmarshal(itemBt, &cartPromotionItemResult)
	cartPromotionItemResult.PromotionMessage = "众筹活动"

	global.Log.Info("打印所需的SKU", zap.Any("SkuId", productAndCrowdFundingResult.ProductSkuId))

	originalPrice := productAndCrowdFundingResult.OriginalPrice
	reduceAmount := originalPrice - productAndCrowdFundingResult.CftThaliPrice
	cartPromotionItemResult.RealStock = productAndCrowdFundingResult.SkuStock - productAndCrowdFundingResult.SkuLockStock
	cartPromotionItemResult.ReduceAmount = reduceAmount
	cartPromotionItemResult.Integration = productAndCrowdFundingResult.GiftPoint
	cartPromotionItemResult.Growth = productAndCrowdFundingResult.GiftGrowth
	resOrderConfirmResult.CartPromotionItemList = append(resOrderConfirmResult.CartPromotionItemList, cartPromotionItemResult)

	// 运费
	resOrderConfirmResult.CalcAmount.FreightAmount = 0
	resOrderConfirmResult.CalcAmount.PayAmount = productAndCrowdFundingResult.CftThaliPrice
	resOrderConfirmResult.CalcAmount.PromotionAmount = reduceAmount
	resOrderConfirmResult.CalcAmount.TotalAmount = productAndCrowdFundingResult.OriginalPrice

	//global.Log.Info("打印一下价格", zap.Any("totalAmount", totalAmount), zap.Any("promotionAmount", promotionAmount))

	app.Response(http.StatusOK, ctx.OK, resOrderConfirmResult)
}

type cartPromotionItem struct {
	CreateDate        time.Time `json:"createDate"`
	DeleteStatus      int64     `json:"deleteStatus"`
	Growth            int64     `json:"growth"`
	Id                int64     `json:"id"`
	Integration       int64     `json:"integration"`
	MemberId          int64     `json:"memberId"`
	MemberNickname    string    `json:"memberNickname"`
	ModifyDate        time.Time `json:"modifyDate"`
	Price             float64   `json:"price"`
	ProductAttr       string    `json:"productAttr"`
	ProductBrand      string    `json:"productBrand"`
	ProductCategoryId int64     `json:"productCategoryId"`
	ProductId         int64     `json:"productId"`
	ProductName       string    `json:"productName"`
	ProductPic        string    `json:"productPic"`
	ProductSkuCode    string    `json:"productSkuCode"`
	ProductSkuId      int64     `json:"productSkuId"`
	ProductSn         string    `json:"productSn"`
	ProductSubTitle   string    `json:"productSubTitle"`
	PromotionMessage  string    `json:"promotionMessage"`
	Quantity          int       `json:"quantity"`
	RealStock         int64     `json:"realStock"`
	ReduceAmount      float64   `json:"reduceAmount"`

	ServiceIds string `json:"serviceIds" gorm:"service_ids"` // 以逗号分割的产品服务：1->无忧退货；2->快速退款；3->免费包邮

	// sms_crowd_funding
	CfId           int64     `json:"cfId" gorm:"cf_id"`
	CfTitle        string    `json:"cfTitle" gorm:"cf_title"`                // 活动标题
	CfDeliveryDate time.Time `json:"cfDeliveryDate" gorm:"cf_delivery_date"` // 预估发货日期

	// sms_crowd_funding_thali
	CftId               int64     `json:"cftId" gorm:"cft_id"`
	CftTitle            string    `json:"cftTitle" gorm:"cft_title"`                         // 套餐标题
	CftDescription      string    `json:"cftDescription" gorm:"cft_description"`             // 套餐描述
	CftSort             int64     `json:"cftSort" gorm:"cft_sort"`                           // 排序
	CftThaliPrice       float64   `json:"cftThaliPrice" gorm:"cft_thali_price"`              // 套餐价格
	CftThaliDiscount    int64     `json:"cftThaliDiscount" gorm:"cft_thali_discount"`        // 套餐折扣
	CftThaliCount       int64     `json:"cftThaliCount" gorm:"cft_thali_count"`              // 限制数量
	CftLockThaliCount   int64     `json:"cftLockThaliCount" gorm:"cft_lock_thali_count"`     // 已锁数量
	CftThaliLimitStatus int64     `json:"cftThaliLimitStatus" gorm:"cft_thali_limit_status"` // 每人是否限购，0不限购，1限购
	CftThaliLimit       int64     `json:"cftThaliLimit" gorm:"cft_thali_limit"`              // 每人限购数量
	CftStatus           int64     `json:"cftStatus" gorm:"cft_status"`                       // 套餐状态，0 已结束，1 进行中
	CftCreateTime       time.Time `json:"cftCreateTime" gorm:"cft_create_time"`              // 创建时间

}

type resOrderConfirm struct {
	CalcAmount struct {
		FreightAmount   float64 `json:"freightAmount"`
		PayAmount       float64 `json:"payAmount"`
		PromotionAmount float64 `json:"promotionAmount"`
		TotalAmount     float64 `json:"totalAmount"`
	} `json:"calcAmount"`
	CartPromotionItemList   []cartPromotionItem `json:"cartPromotionItemList"`
	CouponHistoryDetailList []struct {
		CategoryRelationList []struct {
			CouponId            int    `json:"couponId"`
			Id                  int    `json:"id"`
			ParentCategoryName  string `json:"parentCategoryName"`
			ProductCategoryId   int    `json:"productCategoryId"`
			ProductCategoryName string `json:"productCategoryName"`
		} `json:"categoryRelationList"`
		Coupon struct {
			Amount       int       `json:"amount"`
			Code         string    `json:"code"`
			Count        int       `json:"count"`
			EnableTime   time.Time `json:"enableTime"`
			EndTime      time.Time `json:"endTime"`
			Id           int       `json:"id"`
			MemberLevel  int       `json:"memberLevel"`
			MinPoint     int       `json:"minPoint"`
			Name         string    `json:"name"`
			Note         string    `json:"note"`
			PerLimit     int       `json:"perLimit"`
			Platform     int       `json:"platform"`
			PublishCount int       `json:"publishCount"`
			ReceiveCount int       `json:"receiveCount"`
			StartTime    time.Time `json:"startTime"`
			Type         int       `json:"type"`
			UseCount     int       `json:"useCount"`
			UseType      int       `json:"useType"`
		} `json:"coupon"`
		CouponCode          string    `json:"couponCode"`
		CouponId            int       `json:"couponId"`
		CreateTime          time.Time `json:"createTime"`
		GetType             int       `json:"getType"`
		Id                  int       `json:"id"`
		MemberId            int       `json:"memberId"`
		MemberNickname      string    `json:"memberNickname"`
		OrderId             int       `json:"orderId"`
		OrderSn             string    `json:"orderSn"`
		ProductRelationList []struct {
			CouponId    int    `json:"couponId"`
			Id          int    `json:"id"`
			ProductId   int    `json:"productId"`
			ProductName string `json:"productName"`
			ProductSn   string `json:"productSn"`
		} `json:"productRelationList"`
		UseStatus int       `json:"useStatus"`
		UseTime   time.Time `json:"useTime"`
	} `json:"couponHistoryDetailList"`
	IntegrationConsumeSetting model.UmsIntegrationConsumeSetting `json:"integrationConsumeSetting"`
	MemberIntegration         int                                `json:"memberIntegration"`
	MemberReceiveAddressList  []model.UmsMemberReceiveAddress    `json:"memberReceiveAddressList"`
}
